package com.liulin.cdse.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.liulin.cdse.entity.Manager;
import com.liulin.cdse.entity.Supplier;
import com.liulin.cdse.exception.AccountExistException;
import com.liulin.cdse.service.SupplierService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;

/**
 * @ClassName SupplierController
 * @Project cdse
 * @Package_name com.liulin.cdse.controller.admin
 * @Description todo
 * @Author 1354414
 * @Data 2025/5/20
 */
@Slf4j
@Controller
@RequestMapping("admin/supplier")
public class SupplierController {
    @Autowired
    private SupplierService supplierService;

    @GetMapping("add")
    public String add() {
        return "supplier_add";
    }

    @PostMapping("add")
    public String add(Supplier supplier, Model model) {
        supplier.setStatus('y');
        try {
            supplierService.add(supplier);
        } catch (AccountExistException e) {
            model.addAttribute("msg", "用户名重复");
            return "supplier_add";
        }
        model.addAttribute("msg", "添加成功");
        return "supplier_add";
    }

    @GetMapping("list")
    public String list(Model model) {
        List<Supplier> suppliers = supplierService.list();
        model.addAttribute("suppliers", suppliers);
        return "supplier_list";
    }

    @GetMapping("update/{id}")
    public String update(@PathVariable int id, Model model) {
        Supplier supplier = supplierService.getById(id);
        model.addAttribute("supplier", supplier);
        return "supplier_update";
    }

    @PostMapping("update")
    public String update(Supplier supplier, RedirectAttributes redirectAttributes) {
        log.debug("manager:{}", supplier);
        QueryWrapper<Supplier> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", supplier.getName());
        if(supplierService.getOne(queryWrapper) == null) {
            supplierService.updateById(supplier);
            return "redirect:/admin/supplier/list";
        }
        redirectAttributes.addFlashAttribute("msg","供应商重复");
        return "redirect:/admin/supplier/update/"+supplier.getId();
    }

    @GetMapping("del/{id}")
    public String del(@PathVariable int id){
        supplierService.removeById(id);
        return "redirect:/admin/supplier/list";
    }
}
